package com.frank.towerrush.view;

import com.frank.towerrush.util.SystemParameter.SystemString;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public abstract class BaseSurfaceView extends SurfaceView implements SurfaceHolder.Callback, Runnable {
    public static final int REFRESH_SPEED_VERY_HIGH = 20;
    public static final int REFRESH_SPEED_HIGH = 50;
    public static final int REFRESH_SPEED_NORMAL = 75;
    public static final int REFRESH_SPEED_SLOW = 100;

    protected Thread thread;
    protected SurfaceHolder holder;
    protected Paint paint;
    protected boolean isRun;
    protected int refresh;

    public BaseSurfaceView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public BaseSurfaceView(Context context) {
        super(context);
        init();
    }

    private void init() {
        holder = getHolder();
        holder.addCallback(this);
        paint = new Paint();
    }

    @Override
    public void run() {
        while (isRun) {
            paint();
            update();

            try {
                Thread.sleep(refresh);
            } catch (InterruptedException e) {
                Log.e(SystemString.APP_NAME, Thread.currentThread().getName() + ":" + getClass().getName() + " run()",
                        e);
            }
        }
    }

    public abstract void onUpdate();

    public abstract void onPaint(Canvas canvas, Paint paint);

    private void update() {
        onUpdate();
    }

    private void paint() {
        Canvas canvas = null;
        try {
            canvas = holder.lockCanvas();
            if (null != canvas) {
                canvas.drawColor(Color.BLACK);
                onPaint(canvas, paint);
            }
        } catch (Exception e) {
            Log.e(SystemString.APP_NAME, Thread.currentThread().getName() + ":" + getClass().getName() + " paint()", e);
        } finally {
            if (canvas != null) {
                holder.unlockCanvasAndPost(canvas);
            }
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        isRun = false;
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        isRun = true;
        thread = new Thread(this);
        thread.start();
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

}
